/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.util.List;

import models.Category;
import models.User;

import play.mvc.*;
import play.i18n.Messages;
import play.data.validation.Valid;
import play.db.jpa.JPA;

/**
 *
 * @author Doudoupe
 */
@With(Secure.class)
public class Categories extends Controller {

    public static User user;

    @Before
    static void setConnectedUser() {
        if (Security.isConnected()) {
            user = User.find("byUsername", Security.connected()).first();
            renderArgs.put("user", user);
        }
    }

    public static void list() {
        List<Category> entities = models.Category.find("order by id desc").fetch();
        render(entities);
    }

    public static void create(Category entity) {
        render(entity);
    }
    
    public static void showCat(Long id)
    {
        Category entities = Category.findById(id);
        render(entities);
        
        
        
    }
    
    public static void edit(Long id) {
        Category entity = Category.findById(id);
        render(entity);
    }

    public static void delete(Long id) {
        Category entity = Category.findById(id);
        entity.delete();
        flash.success(Messages.get("Categories.deleted"));
        Categories.list();
    }

    public static void save(@Valid Category entity) {

        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            render("@create", entity);
        } else {

            entity.save();
            flash.success(Messages.get("Categories.created"));
            Categories.list();
        }
    }

    public static void update(Long id, @Valid Category entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            render("@edit", entity);
        } else {

            entity.id = id;
            entity = entity.merge();
            entity.save();
            flash.success(Messages.get("Categories.updated"));
            Categories.list();
        }

    }
}
